package com.shenmazg6.ex;

import com.alibaba.fastjson2.JSON;
import com.shenmazg6.utils.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: MyGlobalException
 * @date 2022/12/26 14:43
 */

@RestControllerAdvice
@Slf4j
public class MyGlobalException {

    /**
     * 参数错误异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultResponse handleError(MethodArgumentNotValidException e){
        log.warn("Method Argument Not Valid",e);
        BindingResult bindingResult = e.getBindingResult();

        //得到所有错误信息计数
        int errorCount = bindingResult.getErrorCount();
        HashMap<String, String> map = new HashMap<>();
        //错误数大于0
        if (errorCount>0){
            //得到所有错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //迭代错误
            fieldErrors.forEach((fieldError)->{
                //错误信息
                String field = fieldError.getField();
                log.debug("属性：{},传来的值是：{},出错的提示消息：{}",
                        field,fieldError.getRejectedValue(),fieldError.getDefaultMessage());

                map.put(field,fieldError.getDefaultMessage());
            });

            return ResultResponse.FAILED(400, "参数错误", map);
        }else{
            return ResultResponse.FAILED(500, "未知错误");
        }
    }

    //空指针异常
    @ExceptionHandler(value = NullPointerException.class)
    public ResultResponse nullPointerExceptionHandler(NullPointerException ex) {
        ex.printStackTrace();
        return ResultResponse.FAILED(500, "NullPointerException捕获了");
    }

    //类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public ResultResponse classCastExceptionHandler(ClassCastException ex) {
        ex.printStackTrace();
        return ResultResponse.FAILED(500, "ClassCastException捕获了");
    }

    //IO异常
    @ExceptionHandler(IOException.class)
    public ResultResponse iOExceptionHandler(IOException ex) {
        ex.printStackTrace();
        return ResultResponse.FAILED(500, "IOException捕获了");
    }

}
